import 'package:flutter_admin/pages/common/cry/cry_all.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/api/odoo/base_stationuser_odoo_api.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/base_productionstation.dart';
import 'package:flutter_admin/models/odoo/base_stationuser.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:quiver/strings.dart';


class ConfigurePostratioList extends StatefulWidget {
  ConfigurePostratioList({Key? key,required this.baseProductionstation,}) : super(key: key);
  final BaseProductionstation? baseProductionstation;
  @override
  _ConfigurePostratioListState createState() =>
      _ConfigurePostratioListState();
}

class _ConfigurePostratioListState
    extends State<ConfigurePostratioList> {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  BaseStationuser baseStationuser = BaseStationuser();
  List<BaseStationuser> baseStationuserList = [];
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _loadData();
    });
  }

  @override
  Widget build(BuildContext context) {
    int i = 0;
    var table = DataTable(
      columns: [
        DataColumn(label: Text('序号')),
        DataColumn(label: Container(child: Text('人员名称'))),
        DataColumn(label: Container(child: Text('岗位'))),
        DataColumn(label: Container(child: Text('岗位系数%'))),
      ],
      rows: this.baseStationuserList.map((baseStationuser) {
        int rowIndex = i + 1;
        var result = DataRow(
            cells: [
              DataCell(Text((rowIndex).toString())),
              DataCell(Text(baseStationuser.username ?? '--')),
              DataCell(Text(baseStationuser.job != "false"?baseStationuser.job!:'--')),
              DataCell(CryInputNum(
                // width: 150,
                padding: 5,
                value: baseStationuser.postratio,
                onSaved: (v) {
                  baseStationuser.postratio = v;
                },
              ),onTap: ()=>null),
            ]
        );
        i++;
        return result;
      }).toList(),
    );

    var buttonBar = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
          label: S.of(context).save,
          onPressed: () {
            FormState form = formKey.currentState!;
            form.save();
            bool flag = false;
            num sum = 0;
            for(var i=0; i< baseStationuserList.length; i++){
              if(baseStationuserList[i].postratio == 0){
                flag = true;
                break;
              }
              sum += baseStationuserList[i].postratio!;
            }
            if(flag){
              CryUtils.message("请配置岗位系数");
              return ;
            }
            if(sum!=100){
              CryUtils.message("岗位系数百分比不等于100，请重新填写");
              return ;
            }
            List saveData = baseStationuserList
                .map((e) => {"user_id":int.parse(e.staffId!),"postratio":e.postratio})
                .toList();
            BaseStationuserOdooApi.batchUpdateUser(saveData).then((ResponseBodyApi res) {
              if (!res.success!) {
                // CryUtils.message(res.message!);
                return;
              }
              Navigator.pop(context, true);
              CryUtils.message(S.of(context).saved);
            });
          },
          iconData: Icons.save,
        ),
        CryButton(
          label: S.of(context).cancel,
          onPressed: () {
            Navigator.pop(context);
          },
          iconData: Icons.cancel,
        )
      ],
    );
    var result = Scaffold(
      appBar: AppBar(
        leading: Builder(
          builder: (BuildContext context) {
            final ModalRoute<Object?>? parentRoute = ModalRoute.of(context);
            final bool canPop = parentRoute?.canPop ?? false;
            if (canPop) {
              return BackButton();
            } else {
              return SizedBox.shrink();
            }
          },
        ),
        title: Text('配置岗位系数'),
      ),
      body:  SingleChildScrollView(
        child: Column(
          children: [Container(width:650,child: Form(
            key: formKey,
            child: table,))
          ],
        ),
      ),
      bottomNavigationBar: buttonBar,
    );
    return SizedBox(
      width: 650,
      height: 650,
      child: result,
    );
  }



  _loadData() async {
    baseStationuser.stationId = widget.baseProductionstation!.id;
    ResponseBodyApi responseBodyApi =
    await BaseStationuserOdooApi.postraioList(data: {
      "domainList": baseStationuser.toDomainListToo()
    });
    if (responseBodyApi.success!) {
      baseStationuserList = [];
      responseBodyApi.data.forEach((element) {
        baseStationuserList.add(BaseStationuser.fromMap(element));
      });
      setState(() {});
    }
  }

}
